package com.xiaoyu.lanling.feature.vip.activity

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.fragment.app.FragmentTransaction
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.activity.base.BaseFragment
import com.xiaoyu.lanling.event.vip.VipTypeUpdateEvent
import com.xiaoyu.lanling.feature.user.model.UserExtra
import com.xiaoyu.lanling.feature.vip.fragment.VipMineFragment
import com.xiaoyu.lanling.feature.vip.fragment.VipMineNotVipFragment
import com.xiaoyu.lanling.router.Router
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class VipMineActivity : AppCompatToolbarActivity() {

    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState)
        setLightStatusBar()
        setContentView(R.layout.vip_mine_activity)
        initToolbar()

        initView()
        initData()
        initEvent()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        if (UserExtra.instance.isVip)
            menuInflater.inflate(R.menu.menu_vip_mine, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.setting -> {
                Router.instance.gotoPrivilegeSetting(this)
            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun initView() {
        title = getString(R.string.vip_mine_title)
    }

    private fun initData() {
        updateLayout()
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: VipTypeUpdateEvent) {
                updateLayout()
            }
        })
    }

    private fun updateLayout() {
        if (isDestroyed) {
            return
        }

        val fragment: BaseFragment = if (UserExtra.instance.isVip) VipMineFragment() else VipMineNotVipFragment()
        val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.container, fragment)
        fragmentTransaction.commit()
    }
}